<template>
  <div class="addBrand-container">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :inline="true"
      label-width="180px"
      class="demo-ruleForm"
    >
      <el-form-item label="套餐名称:" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请填写套餐名称"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="套餐分类:" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择套餐分类">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐价格:" prop="price">
        <el-input v-model="formData.price" placeholder="请设置套餐价格" />
      </el-form-item>
      <el-form-item label="套餐菜品:">
        <div class="flavorBox">
          <el-button
            v-if="formData.setmealDishes.length == 0"
            type="primary"
            @click="handleAdd"
            >+ 添加菜品</el-button
          >
          <div v-if="formData.setmealDishes.length != 0" class="flavor">
            <el-button type="primary" @click="handleAdd">+ 添加菜品</el-button>
            <el-table :data="formData.setmealDishes" style="width: 100%">
              <el-table-column
                prop="name"
                label="名称"
                width="180"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="price"
                label="原价"
                width="180"
              ></el-table-column>
              <el-table-column prop="copies" label="份数" align="center">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.copies"
                    size="small"
                    :min="1"
                    :max="99"
                    label="描述文字"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180px;" align="center">
                <template #default="scope">
                  <el-button
                    size="small"
                    class="delBut"
                    @click="handleDel(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="套餐图片:" prop="image" class="uploadImg">
        <el-upload
          class="avatar-uploader"
          action="/common/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-change="onChange"
          ref="upload"
        >
          <!-- <img
            v-if="formData.image"
            :src="'@/assets/dish-images/' + formData.image"
            class="avatar"
          /> -->
          <img v-if="formData.image" :src="formData.image" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="套餐描述:" prop="description" class="address">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="套餐描述，最长200字"
          maxlength="777"
        />
      </el-form-item>
      <div class="subBox">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submitForm()">保存</el-button>
        <!-- <el-button v-if="actionType == 'add'" type="primary" class="continue" @click="submitForm('ruleForm','goAnd')">保存并继续添加套餐</el-button> -->
      </div>
    </el-form>

    <el-dialog title="添加菜品" class="addDishList" v-model="open" width="60%">
      <el-input
        v-model="queryParamsName"
        placeholder="请输入菜品名称进行搜索"
        class="seachDish"
        style="width: 250px"
        clearable
      >
        <template #prefix>
          <el-icon style="cursor: pointer" @click="handleQuery"
            ><Search
          /></el-icon>
        </template>
      </el-input>
      <!-- <AddDish ref="adddish" :check-list="checkList" :seach-key="seachKey" @checkList="getCheckList" /> -->

      <div class="addDishCon">
        <div class="leftCont">
          <!-- <div v-show="seachKey.trim() == ''" class="tabBut">
                        <span v-for="(item, index) in dishType" :key="index" :class="{act:index == keyInd}" @click="checkTypeHandle(index, item.id)">{{ item.name }}</span>
                    </div> -->
          <div v-if="dishList.length == 0" style="padding-left: 10px">
            暂无菜品!
          </div>
          <el-checkbox-group v-else v-model="checkedList">
            <div v-for="(item, index) in dishList" :key="index" class="items">
              <el-checkbox :key="index" :label="item" :disabled="!item.status">
                <div class="item">
                  <span>{{ item.name }}</span>
                  <span>{{ item.status == 0 ? "停售" : "在售" }}</span>
                  <span>{{ item.price }}</span>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <div class="ritCont">
          <div class="tit">已选菜品({{ checkedList.length }})</div>
          <div class="items">
            <div v-for="(item, ind) in checkedList" :key="item.id" class="item">
              <span>{{ item.name }}</span>
              <span class="price">￥ {{ item.price }} </span>
              <span class="del" @click="handleRemove(ind)"
                ><img src="@/assets/icons/btn_clean@2x.png" alt=""
              /></span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="handlePush">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import { validPrice } from "@/utils/validate";
import { getSetmealById, addSetmeal, editSetmeal } from "@/api/setmeal/setmeal";
import { getListByType as getCategoryListByType } from "@/api/category/category";
import { getList } from "@/api/dish/dish";
import { ElMessage } from "element-plus";

const props = defineProps({
  id: {
    type: String,
    default: undefined,
  },
});
const emits = defineEmits(["close"]);

const formRef = ref();
const formData = ref({
  idType: "",
  name: "",
  code:"",
  price: "",
  image: "",
  description: "",
  dishList:[],
  setmealDishes: [],
  status: 1,
  categoryId: "",
});
const formRules = reactive({
  name: [{ required: true, message: "请填写套餐名称", trigger: "blur" }],
  categoryId: [
    { required: true, message: "请选择套餐分类", trigger: "change" },
  ],
  price: [{ required: true, validator: validPrice, trigger: "blur" }],
});
const categoryList = ref([]);

const open = ref(false);
const queryParamsName = ref("");
const dishList = ref([]);
const checkedList = ref([]);

const imageUrl = ref("");

/* 获取套餐分类、获取套餐对象、获取口味列表 */
const init = () => {
  if (props.id) {
    getSetmealById({ id: props.id }).then((res) => {
      formData.value = res.data;
      formData.value.price = (formData.value.price / 100).toFixed(2);
      formData.value.idType = props.id;
    });
  }
  getCategoryListByType({ type: 2 }).then((res) => {
    categoryList.value = res.data;
  });
};
init();

/* 删除菜品按钮 */
const handleDel = (index) => {
  formData.value.setmealDishes.splice(index, 1);
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      formData.value.price = formData.value.price * 100;
      if (!formData.value.idType) {
        addSetmeal(formData.value).then((res) => {
          ElMessage({ type: "success", message: res.data });
          close();
          getSetmealList();
        });
      } else {
        editSetmeal(formData.value).then((res) => {
          ElMessage({ type: "success", message: res.data });
          close();
          getSetmealList();
        });
      }
    }
  });
};

/* 添加菜品按钮 */
const handleAdd = () => {
  open.value = true;
  checkedList.value = [];
  handleQuery();
};

/* 查询菜品 */
const handleQuery = () => {
  const params = {
    page: 1,
    pageSize: 100,
    name: queryParamsName.value,
  };
  getList(params).then((res) => {
    dishList.value = res.data.records;

    dishList.value = dishList.value.map(item => ({
   ...item,
  price: (item.price / 100).toFixed(2)
}));
    
  });
};

/* 添加菜品 */
const handlePush = () => {
  checkedList.value.forEach((item) => {
    formData.value.setmealDishes.push({
      dishId: item.id,
      name: item.name,
      price: item.price,
      copies: 1,
    });
  });
  open.value = false;
};

/* 删除菜品操作 */
const handleRemove = (index) => {
  checkedList.value.splice(index, 1);
};

const handleAvatarSuccess = (response, file, fileList) => {
  // 拼接down接口预览
  if (response.code === 0 && response.msg === "未登录") {
    window.top.location.href = "/backend/page/login/login.html";
  } else {
    // this.imageUrl = `/common/download?name=${response.data}`;
    // this.ruleForm.image = response.data;
    formData.value.image = response.data;
  }
};

const onChange = (file) => {
  if (file) {
    const suffix = file.name.split(".")[1];
    const size = file.size / 1024 / 1024 < 2;
    if (["png", "jpeg", "jpg"].indexOf(suffix) < 0) {
      this.$message.error("上传图片只支持 png、jpeg、jpg 格式！");
      this.$refs.upload.clearFiles();
      return false;
    }
    if (!size) {
      this.$message.error("上传文件大小不能超过 2MB!");
      return false;
    }
    return file;
  }
};

const close = () => {
  emits("close");
};

const getSetmealList = () => {
  emits("getSetmealList");
};
</script>

<style lang="scss" scoped>
.cont .delBut {
  padding: 0 10px;
  cursor: pointer;
  line-height: 40px;
}

.uploadImg .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.addDish .el-input {
  width: 130px;
}
.addDish .el-input-number__increase {
  border-left: solid 1px #ffe1ca;
  background: #fff3ea;
}
.addDish .el-input-number__decrease {
  border-right: solid 1px #ffe1ca;
  background: #fff3ea;
}
.addDish input {
  border: 1px solid #ffe1ca;
}
.addDish .table {
  border: solid 1px #ebeef5;
  border-radius: 3px;
}
.addDish .table th {
  padding: 5px 0;
}
.addDish .table td {
  padding: 7px 0;
}
.addDishList .seachDish {
  position: absolute;
  top: 16px;
  right: 60px;
}

.addDish {
  width: 777px;
}
.addDish .addBut {
  background: #ffc200;
  display: inline-block;
  padding: 0px 20px;
  border-radius: 3px;
  line-height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #333333;
  font-weight: 500;
}
.addDish .content {
  background: #fafafb;
  padding: 20px;
  border: solid 1px #ccc;
  border-radius: 3px;
}
.addDishCon {
  padding: 0 20px;
  display: flex;
  line-height: 40px;
}
.addDishCon .leftCont {
  display: flex;
  border-right: solid 2px #e4e7ed;
  width: 60%;
  padding: 15px;
}
.addDishCon .leftCont .tabBut {
  width: 110px;
}
.addDishCon .leftCont .tabBut span {
  display: block;
  text-align: center;
  border-right: solid 2px #f4f4f4;
  cursor: pointer;
}
.addDishCon .leftCont .act {
  border-color: #ffc200 !important;
  color: #ffc200 !important;
}

.addDishCon .leftCont .items {
  border-bottom: solid 1px #f4f4f4;
  padding: 5px;
  width: 250px;
}
.addDishCon .leftCont .items .item {
  display: flex;
  padding-right: 20px;
}
.addDishCon .ritCont {
  width: 40%;
  padding: 0 15px;
}
.addDishCon .ritCont .item {
  box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
  display: flex;
  text-align: center;
  padding: 0 10px;
  margin-bottom: 20px;
  border-radius: 6px;
  color: #818693;
}
.addDishCon .ritCont .item span:first-child {
  text-align: left;
  color: #20232a;
}
.addDishCon .ritCont .item .price {
  display: inline-block;
  flex: 1;
}
.addDishCon .ritCont .item .del {
  cursor: pointer;
}
.addDishCon .ritCont .item .del img {
  position: relative;
  top: 5px;
  width: 20px;
}

.addDishCon .el-checkbox__label {
  width: 100%;
}
#combo-add-app .setmealFood .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

#combo-add-app .uploadImg .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
</style>
